import axios from 'axios'
import qs from 'qs'
import {
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'

import defaultSettings from '@/settings' // 引用配置
const { duration } = defaultSettings // 获取时间配置
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: duration.timeout, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    // 'Content-Type': 'application/json;charset=utf-8'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
      config.headers['ACCESS_TOKEN'] = getToken()
    }
    if (config.method === 'post') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log(response)
    if (response.status === 200) {
      // console.log(response.data)
      if (response.data.code === 200 || response.data.code === 20000) {
        return Promise.resolve(response.data)
      } else if (response.data.code === 401) {
        Message({
          message: '登录超时，即将跳到登录',
          type: 'warning',
          duration: duration.warning
        })
        setTimeout(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, 3000)
      } else if (response.data.code === 404) {
        Message({
          message: response.data.msg,
          type: 'error',
          duration: duration.error
        })
        setTimeout(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, 3000)
      } else if (response.data.code > 499) {
        Message({
          message: response.data.msg,
          type: 'error',
          duration: duration.error
        })
        return Promise.resolve(response.data)
      } else {
        return Promise.resolve(response.data)
      }
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    switch (error.response.status) {
      case 400: // 400：1、语义有误，当前请求无法被服务器理解;2、请求参数有误。
        Message({
          message: '请求有误',
          type: 'error',
          duration: duration.error
        })
        break
      case 401: // 402：当前请求需要用户验证。
        Message({
          message: '身份验证有误，请重新登录',
          type: 'error',
          duration: duration.error
        })
        setTimeout(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, duration.error)
        break
      case 403: // 403：服务器已经理解请求，但是拒绝执行它
        Message({
          message: '服务器拒绝请求',
          type: 'error',
          duration: duration.error
        })
        break
      case 404: // 404：未找到服务器
        Message({
          message: '未找到服务器',
          type: 'error',
          duration: duration.error
        })
        break
      case 405: // 405：未找到服务器
        Message({
          message: '服务器拒绝请求方法',
          type: 'error',
          duration: duration.error
        })
        break
      case 408: // 408：未找到服务器
        Message({
          message: '请求超时',
          type: 'error',
          duration: duration.error
        })
        break
      case 410: // 410：未找到服务器
        Message({
          message: '请求冲突',
          type: 'error',
          duration: duration.error
        })
        break
      case 414: // 414：请求的URI 长度超过了服务器能够解释的长度，因此服务器拒绝对该请求提供服务。
        Message({
          message: '请求地址过长',
          type: 'error',
          duration: duration.error
        })
        break
      case 500: // 500：服务器遇到了一个未曾预料的状况，导致了它无法完成对请求的处理
        Message({
          message: '服务器有误',
          type: 'error',
          duration: duration.error
        })
        break
      case 501: // 501：服务器无法识别请求方法
        Message({
          message: '服务器无法识别请求方法',
          type: 'error',
          duration: duration.error
        })
        break
      case 502: // 502：服务器接收到无效的响
        Message({
          message: '服务器接收到无效的响应',
          type: 'error',
          duration: duration.error
        })
        break
      default:
        console.log(error)
        Message({
          message: '未知状态错误',
          type: 'error',
          duration: duration.error
        })
    }
    return Promise.reject(error.response)
  }
)

export default service
